package com.heba.greenmulu.scan;

import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heba.Cfg;
import com.heba.Debug;
import com.heba.adapter.category.OptionExpandableAdapter;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.category.ItemProductOptionObject;
import com.heba.bean.category.OptionLevel2Object;
import com.heba.bean.category.OptionLevel3Object;
import com.heba.bean.expandgroup.DataListTree;
import com.heba.config.CommonConfig;
import com.heba.event.MessageEvent;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.utils.GlideUtil;
import com.loopj.android.http.RequestParams;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 产品筛选
 * Created by jason on 2020/1/8.
 */
public class ItemProductOptionCategoryActivity extends BaseActivity {

    private RecyclerView rv_left;
    private RecyclerView rv_right;
    private Button btn_confirm;

    private QuickAdapter recycleAdapter;

    private int categoryID;    //分类id
    private int categoryLevel;   //分类层级

    /**
     * 筛选分类二級列表adapter
     */
    private OptionExpandableAdapter optionExpandableAdapter;

    /**
     * 二级筛选分类列表数据
     */
    private List<DataListTree<OptionLevel2Object, OptionLevel3Object>> mDataListTrees;

    /**
     * 所有筛选分类数据
     */
    private List<ItemProductOptionObject> optionObjects;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_product_filter);
        initTopbar();
        findViewById();
        initView();
        getOptionListData();
    }

    @Override
    protected void findViewById() {
        rv_left = findViewById(R.id.rv_left);
        rv_right = findViewById(R.id.rv_right);
        btn_confirm = findViewById(R.id.btn_confirm);
    }

    @Override
    protected void initView() {
        txt_title.setText(getResources().getString(R.string.scan_filter));

        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            categoryID = bundle.getInt(CommonConfig.CATEGORY_ID, 0);
            categoryLevel = bundle.getInt(CommonConfig.CATEGORY_LEVEL, 0);
        }

        optionObjects = new ArrayList<>();
        mDataListTrees = new ArrayList<>();

        List<Integer> isCheck = new ArrayList<>();
        //默认选中第一个item
        isCheck.add(0);

        recycleAdapter = new QuickAdapter<ItemProductOptionObject>(optionObjects) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_scan_category_product;
            }

            @Override
            public void convert(VH holder, ItemProductOptionObject data, int position) {
                ImageView iv_icon = holder.getView(R.id.iv_icon);
                TextView tv_category = holder.getView(R.id.tv_category);
                tv_category.setText(data.getOptionName());

                GlideUtil.loadImageWithDefaultPlaceHolder(ItemProductOptionCategoryActivity.this, data.getIcon(), iv_icon);

                List<OptionLevel2Object> level2Objects = data.getOptionLevel2();

                if (isCheck.contains(position)) {
                    holder.itemView.setSelected(true);
                    mDataListTrees.clear();
                    for (int i = 0; i < level2Objects.size(); i++) {
                        OptionLevel2Object object = level2Objects.get(i);
                        mDataListTrees.add(new DataListTree<>(object, object.getOptionLevel3()));
                    }
                    optionExpandableAdapter.setData(mDataListTrees);
                    optionExpandableAdapter.notifyDataSetChanged();
                } else {
                    holder.itemView.setSelected(false);
                }

                /**
                 * 更新选中的item
                 */
                holder.itemView.setOnClickListener(v -> {
                    if (isCheck.contains(position))
                        return;
                    isCheck.clear();
                    isCheck.add(position);
                    notifyDataSetChanged();

                    /**
                     * 更新二级分类数据
                     */
                    mDataListTrees.clear();
                    for (int i = 0; i < level2Objects.size(); i++) {
                        OptionLevel2Object object = level2Objects.get(i);
                        mDataListTrees.add(new DataListTree<>(object, object.getOptionLevel3()));
                    }
                    optionExpandableAdapter.setData(mDataListTrees);
                    optionExpandableAdapter.notifyDataSetChanged();
                });
            }
        };

        /**
         * 设置layoutManager布局
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        rv_left.setLayoutManager(layoutManager);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置Adapter
        rv_left.setAdapter(recycleAdapter);

        /**
         * 二級列表recyclerview佈局設置
         */
        optionExpandableAdapter = new OptionExpandableAdapter(this);
        optionExpandableAdapter.setData(mDataListTrees);
        rv_right.setLayoutManager(new LinearLayoutManager(this));
        rv_right.setAdapter(optionExpandableAdapter);

        /**
         * 查看结果点击事件
         */
        btn_confirm.setOnClickListener(v -> {
            List<OptionLevel3Object> level3ObjectList = optionExpandableAdapter.getSelectList();
            Debug.Log("筛选Item", "选中的个数是" + level3ObjectList.size());

            /**
             * EventBus通信
             */
            MessageEvent event = new MessageEvent();
            event.setEvent(CommonConfig.OPTION_LIST);
            event.setOptionLevel3ObjectList(level3ObjectList);
            EventBus.getDefault().post(event);
            finishActivity();

        });
    }

    /**
     * 獲取分類數據
     */
    private void getOptionListData() {
        progressDialog.show();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("Categoryid", categoryID);
        params.put("Categorylevel", categoryLevel);
        client.get(Cfg.BaseUrl + "/Product/OptionList", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        optionObjects.clear();
                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                List<ItemProductOptionObject> objects = new Gson().fromJson(array.toString(), new TypeToken<List<ItemProductOptionObject>>() {
                                }.getType());
                                optionObjects.addAll(optionObjects.size(), objects);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        /**
                         * 刷新列表
                         */
                        recycleAdapter.notifyDataSetChanged();

                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }
}
